# -*- coding:utf-8 -*-

import pymysql
import time
import datetime

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='myuse', charset='utf8')

app = Flask(__name__)
api = Api(app)

class add(Resource):
    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', type=int, help='Rate to charge for this resource')
        parser.add_argument('name', type=str, help='Rate to charge for this resource')
        parser.add_argument('age', type=int, help='Rate to charge for this resource')
        self.parser = parser

    def get(self):
        args = self.parser.parse_args()
        cursor = conn.cursor()
        coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        sql = "INSERT INTO person (id, name, age, birthday) VALUES ({}, \"{}\", {}, \"{}\");".format(args["id"], args["name"], args["age"], coolection_time)
        print(sql)
        result=cursor.execute(sql) #执行sql语句，返回sql查询成功的记录数目
        conn.commit()
        return {'res': result}

class dele(Resource):
    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', type=int, help='Rate to charge for this resource')
        self.parser = parser

    def get(self):
        args = self.parser.parse_args()
        cursor = conn.cursor()
        sql = "DELETE FROM person WHERE id={};".format(args["id"])
        result=cursor.execute(sql)
        conn.commit()
        return {'res': result}
        
class modify(Resource):
    def __init__(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', type=int, help='Rate to charge for this resource')
        parser.add_argument('age', type=int, help='Rate to charge for this resource')
        self.parser = parser

    def get(self):
        args = self.parser.parse_args()
        cursor = conn.cursor()
        sql = "UPDATE person SET age={} WHERE id={};".format(args["age"], args["id"])
        result=cursor.execute(sql)
        conn.commit()
        return {'res': result}
        
class query(Resource):

    def get(self):
        cursor = conn.cursor()
        sql = "select * from person"
        result=cursor.execute(sql)
        return {'res': result}

api.add_resource(add, '/add')
api.add_resource(dele, '/dele')
api.add_resource(modify, '/modify')
api.add_resource(query, '/query')

if __name__ == '__main__':
    app.run(debug=True)
